package com.example.mattrigle;

public class CustomAnimation
{
	// ==========================================================
	// Delegate & Callback
	// ==========================================================
    public abstract interface TimerListener {
        public void onTimeUpdate(CustomAnimation obj,long totalTime,long deltaTime);
    }

	//==========================================================
	//Field 
	//==========================================================
	private long peroidTime = 0,startTime = 0,currentTime = 0;
	private boolean running = false;
	private Thread myThread = null;
	
	//==========================================================
	//Properties 
	//==========================================================
	private int Inteval = 300;
	public int getInterval()
	{
		return Inteval;
	}
	public void setInterval(int interval)
	{
		this.Inteval = interval;
	}
	
	//==========================================================
	//Listener Method 
	//==========================================================
	private TimerListener listener = null;
	public void setListener(TimerListener lisneter)
	{
		this.listener = lisneter;
	}
	
	//==========================================================
	//Public Method
	//==========================================================
	public void StartAnimation()
	{
		if(canAnimation())
			StopAnimation();
		running = true;
		peroidTime = 0;
        myThread = new Thread(new UpdateThread());
        myThread.start();
	}
	
	public boolean canAnimation()
	{
		return running;
	}

	public void EndAnimation()
	{
		running = false;
	}
	
	public void StopAnimation()
	{
		running = false;
		boolean retry = true;
		while(retry)
		{
			try {
				if(myThread!=null)
					myThread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}

	//==========================================================
	//Process & Operand Class
	//==========================================================
    private class UpdateThread implements Runnable 
    {
 
        @Override
        public void run() 
        {
        	startTime = System.currentTimeMillis();
        	peroidTime = startTime;
            while(running)
            {
            	currentTime = System.currentTimeMillis();
            	if(listener!=null)
            		listener.onTimeUpdate(CustomAnimation.this, currentTime - startTime, currentTime - peroidTime);
            	
            	try {
					Thread.sleep(Inteval);
				} catch (InterruptedException e) {
				}
            	peroidTime = currentTime;
            }
        }
 
    }

}
